package servlet;

import dao.UsuarioDAO;
import entidade.Usuario;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.registry.infomodel.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.Util;

/**
 *
 * @author luiz
 */
public class ValidaLoginServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Usuario usuario = new Usuario();
        UsuarioDAO usuarioDAO = new UsuarioDAO();
        String login = "";
        String senha = "";
        String codigo = "";
        String digitado = "";
        Util util = new Util();
        login = (util.validaParametro(request.getParameter("login")));
        senha = (util.validaParametro(request.getParameter("senha")));
        codigo = (util.validaParametro(request.getParameter("codigo")));
        digitado = (util.validaParametro(request.getParameter("digitado")));

// request.getRequestDispatcher("listar.jsp").forward(request, response);
        response.setContentType(
                "text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet validaLoginServlet</title>");
            out.println("</head>");
            out.println("<body>");

            if (!digitado.equals(codigo)) {
                response.sendRedirect("/ProjetoIntegrador/login.jsp");
            } else {

                usuario = usuarioDAO.buscar(login);
                if (usuario == null) {
                    response.sendRedirect("/ProjetoIntegrador/login.jsp");
                }
                if (usuarioDAO.buscar(login) == null) {
                    //    out.println("<h1>Login não existe</h1>");
                    response.sendRedirect("/ProjetoIntegrador/login.jsp");
                } else if (!util.verificaParametro(senha)) {
                    //          out.println("<h1>Senha Não Informada</h1>");
                    response.sendRedirect("/ProjetoIntegrador/login.jsp");
                } else if (usuario.getSenha().equals(senha)) {
                //          out.println("<h1>Logado com sucesso</h1>");

                    if (usuario == null) {
                        response.sendRedirect("/ProjetoIntegrador/login.jsp");
                    } else {
                        HttpSession session = request.getSession();
                        session.setAttribute("user", usuario);
                        response.sendRedirect("/ProjetoIntegrador/sistema/principal.jsp");
                    }

                } else if (!usuario.getSenha().equals(senha)) {
                    response.sendRedirect("/ProjetoIntegrador/login.jsp");
                    //        out.println("<h1>Senha Invalida</h1>");
                } else {
                    response.sendRedirect("/ProjetoIntegrador/login.jsp");
                    //            out.println("<h1>Erro ao realizar Login</h1>");
                }
                out.println("</body>");
                out.println("</html>");
            }
        }
    }

    protected void processRequestGET(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // request.getRequestDispatcher("listar.jsp").forward(request, response);
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Erro</title>");
            out.println("</head>");
            out.println("<body>");

            out.println("<h3>Página Invalida</h3>");

            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
